<template>
  <VGroup :style="style">
    <el-select
      v-if="options.length"
      :style="selectStyle"
      v-model="keyValue"
      v-bind="_options"
    >
      <el-option
        v-for="n in options"
        :key="n.value"
        :label="n.label"
        :value="n.value"
      >
      </el-option>
    </el-select>
    <slot :value="slotValue" :input="handleInput"></slot>
  </VGroup>
</template>
<script setup>
const props = defineProps({
  modelValue: { type: [Object, String, Number], default: () => ({}) },
  options: { type: Array, default: () => [] },
  style: { type: [Object, String], default: () => ({}) },
  selectStyle: { type: [Object, String], default: () => ({}) },
  defaultSelect: { type: Boolean, default: true },
  itemProps: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['update:modelValue'])

const keyValue = ref()
const slotValue = ref()

const _options = computed(() => {
  const option = {
    placement: 'bottom',
    multiple: false,
  }
  return Object.assign(option, props?.itemProps)
})

watch(
  () => [keyValue.value, slotValue.value],
  val => {
    const [key, value] = val || []
    if (!props.options.length) {
      emit('update:modelValue', { value })
      return
    }
    emit('update:modelValue', { key, value })
    if (key === undefined && value === undefined) {
      emit('update:modelValue', undefined)
      return
    }
  }
)

watch(
  () => props.options,
  val => {
    if (val.length) {
      keyValue.value = val?.[0]?.value
    }
  },
  { immediate: true }
)

watch(
  () => props.modelValue,
  val => {
    const { key, value } = val || {}
    if (
      ['[object String]', '[object Number]', '[object Array]'].includes(
        Object.prototype.toString.call(val)
      )
    ) {
      slotValue.value = val
      return
    }
    const _options = props.options
    keyValue.value =
      props.defaultSelect && _options?.length && !key
        ? _options?.[0]?.value
        : key
    slotValue.value = value
  },
  { immediate: true }
)

const handleInput = e => {
  slotValue.value = e
}
</script>
